package com.yulinlin.jdbc.session;

import com.yulinlin.core.ISqlTemplate;
import com.yulinlin.core.IWrapperManager;
import com.yulinlin.jdbc.mysql.MysqlWrapperManager;
import com.yulinlin.lang.util.ReflectionUtil;
import com.yulinlin.lang.util.SpringUtil;
import com.yulinlin.core.wrapper.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SqlSession{


    private ISqlTemplate sqlTemplate;

    private IWrapperManager wrapperManager;



    public SqlSession(ISqlTemplate sqlTemplate, IWrapperManager wrapperManager) {
        this.sqlTemplate = sqlTemplate;
        this.wrapperManager = wrapperManager;
    }

    public <E>  List<E> selectList(ISqlWrapper wrapper, Class clazz){
        return sqlTemplate.select(wrapper,clazz);
    }

    public <E>  E selectOne(ISqlWrapper wrapper,Class clazz){
        List<E> list =  this.selectList(wrapper,clazz);
        if(list.size() > 0) {
            return  list.get(0);
        }
        return  null;
    }

    public <K,E>  Map<K,List<E>> selectByGroup(ISqlWrapper wrapper,Class clazz,String key){
        List<E> list =  this.selectList(wrapper,clazz);
        Map<Object,List<E>> map =  new HashMap<>();

        for (E row : list){
            String k =  ReflectionUtil.invokeGetter(row,key);
            List<E> vals  =  map.get(k);
            if(vals == null){
                vals = new ArrayList<>();
                map.put(k,vals);
            }
            vals.add(row);
        }

        return  (Map<K,List<E>>)map;
    }

    public <K,E>  Map<K,E> selectByMap(ISqlWrapper wrapper,Class clazz,String key){
        List<E> list =  this.selectList(wrapper,clazz);
        Map<Object,E> map =  new HashMap<>();

        for (E row : list){
            String k =  ReflectionUtil.invokeGetter(row,key);
            map.put(k,row);
        }

        return ( Map<K,E> ) map;
    }


    //更新操作
    public int execute(ISqlWrapper wrapper){
        return  sqlTemplate.execute(wrapper);
    }


    public <E,R> ISelectWrapper<E,R> ofSelect(R endWrapper){

        return wrapperManager.ofSelect(endWrapper);

    }

    public IInsertWrapper ofInsert(){
        return wrapperManager.ofInsert();
    }

    public <E,R> IUpdateWrapper<E,R> ofUpdate(R endWrapper){
        return wrapperManager.ofUpdate(endWrapper);
    }

    public <E,R> IDeleteWrapper<E,R> ofDelete(R endWrapper){
        return wrapperManager.ofDelete(endWrapper);
    }


    public static SqlSession session(){
        return SpringUtil.getBean(SqlSession.class);
    }
}
